package cn.jhoncy.jproject.framework.config;

import cn.jhoncy.jproject.framework.security.Authentication.CustomAuthenticationProvider;
import cn.jhoncy.jproject.framework.security.Authorization.CustomAccessDecisionManager;
import cn.jhoncy.jproject.framework.security.Authorization.CustomFilterInvocationSecurityMetadataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * web安全配置
 * Created by zhuangqi on 17-4-17.
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //将管理器暴露为Bean
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/","/login").permitAll()
                .anyRequest().authenticated();//所有其他的URL都需要用户进行验证
    }

    /**
     *  1.鉴别是否有权限【鉴权:通过Authentication对象和AuthenticationManager以及AuthenticationProvider互相合作来实现的】
     */

    //1.1将自定义授权器注入为Bean
    @Bean
    public AuthenticationProvider authenticationProvider() {
        AuthenticationProvider authenticationProvider = new CustomAuthenticationProvider();
        return authenticationProvider;
    }
    //1.2注入鉴权器默认处理
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

    /**
     *  2.授予权利【授权：通过GrantedAuthority、AccessDecisionManager和FilterInvocationSecurityMetadataSource或者AccessDecisionVoter等互相合作来实现的】
     */

    //2.1注入授权资源角色授权器
    @Bean
    public CustomFilterInvocationSecurityMetadataSource securityMetadataSource() {
        return new CustomFilterInvocationSecurityMetadataSource();
    }

    //2.2注入授权访问决策器
    @Autowired
    @Bean
    public CustomAccessDecisionManager accessDecisionManager() {
        return new CustomAccessDecisionManager();
    }

}
